export const ONE_DAY = 1000 * 24 * 60 * 60;
export default function (missions, tInterval = 80, {
    type = 'mission',
    inhuman = false,
    mix = false,
    start,
    end,
    limitTimeRange = false,
} = {}) {
  // console.log('计算gantt')
    return new Promise((resolve, ) => {
        const missionList = [...missions];
        let ganttList = [];
        let users = new Map();
        let tStart, tEnd;
        let interval = tInterval;
        const today = Date.parse(new Date().toLocaleDateString());
        const pointer = {
            enable: false,
            x: 0
        }
        let totalWidth = 750;
        if (limitTimeRange || start) {
            tStart = getDate(start).getTime();
        } else {
            tStart = new Date().getTime();
        }
        if (limitTimeRange || end) {
            tEnd = getDate(end).getTime();
        } else {
            tEnd = new Date().getTime();
        }
        for (let index = 0; index < missionList.length; index++) {
            const item = missionList[index];
            if (!item.start || !item.end) {
                missionList.splice(index, 1);
                index--;
            }
        }
        if (!limitTimeRange) {
            for (let item of missionList) {
                //step1 获取时间区间
                const tempStartDate = getDate(item.start).getTime();
                const tempEndDate = getDate(item.end).getTime();
                if (tempStartDate < tStart) {
                    tStart = tempStartDate;
                }
                if (tempEndDate > tEnd) {
                    tEnd = tempEndDate;
                }
                //step2 将任务按用户归属
                let currentUser;
                if (users.has(item.userId)) {
                    currentUser = users.get(item.userId);
                } else {
                    currentUser = {
                        name: item.userName,
                        _id: item.userId,
                        mission: []
                    }
                    users.set(item.userId, currentUser);
                }
                currentUser.mission.push(item);

            }

            //将时间向前/后各扩展一天
            tStart = new Date(tStart - ONE_DAY * 3);
            tEnd = new Date(Math.max(tEnd, today) + ONE_DAY * 3);

            // if (type === 'person') {
            users = [...users.values()];
            totalWidth = interval * ((tEnd - tStart) / (ONE_DAY));
            if (totalWidth < 750) {
                //如果总长小于750 隐藏当前日期标注线（因为丑）
                totalWidth = 750;
                interval = totalWidth / ((tEnd - tStart) / (ONE_DAY));
            } else if (tStart <= today && tEnd >= today) {
                pointer.enable = true;
                pointer.x = (today - tStart.getTime()) / (ONE_DAY) * interval;
            }
        } else {
            //筛选范围内的任务
            for (let i = 0; i < missionList.length; i++) {
                const item = missionList[i];
                const tempStartDate = getDate(item.start).getTime();
                const tempEndDate = getDate(item.end).getTime();
                if (tempStartDate > tEnd || tempEndDate < tStart) {     //如果时间在固定时间范围外则进行剔除
                    missionList.splice(i, 1);
                    i--;
                    continue;
                }
            }
            //totalWidth锁死在750，计算日期间隔
            totalWidth = 750;
            interval = totalWidth / ((tEnd - tStart) / (ONE_DAY));

            if (today >= tStart && today <= tEnd) {
                pointer.enable = true;
                pointer.x = (today - tStart) / (ONE_DAY) * interval;
            }
            tStart = new Date(tStart);
            tEnd = new Date(tEnd);
        }

        tStart = getLocalString(tStart);
        tEnd = getLocalString(tEnd);

        switch (type) {
            case 'mission':
                {
                    ganttList = missionList.map(item => [item]);
                    //向上填充
                    if (mix !== false) {
                        mixGantt(ganttList)
                    }
                    break;
                }
            case 'person':
                {
                    break;
                }
            case 'min':
                {
                    break;
                }
            default:
        }
        ganttList = ganttList.filter(item => {
            if (!item.length) {
                return false;
            } else {
                item.forEach(item => item = Object.assign(item, figureStyle(item, {
                    start: tStart,
                    end: tEnd,
                    interval
                })))
                return true;
            }
        });
        resolve({
            ganttList,
            users,
            start: tStart,
            pointer,
            end: tEnd,
            interval,
            totalWidth,
            oStart: start,
            limitTimeRange,
            oEnd: end,
        })
    })
}


export function getDate(str) {
    if (typeof str == 'string') {
        const tempArr = str.split(/[-/\\_]/);
        return new Date(tempArr[0], tempArr[1] - 1, tempArr[2])
    } else {
        return new Date(str)
    }
}
/**
 * 向数组中特定序号插入元素
 */
function insetIntoArray(array, item, index) {
    return [...array.splice(0, index), item, ...array]
}
const symbols = wx.getSystemInfoSync().platform === 'ios' ? '/' : '-';

export function getLocalString(date) {
    return `${date.getFullYear()}${symbols}${date.getMonth() + 1}${symbols}${date.getDate()}`
}
/**
 * 计算甘特图样式
 */
export function figureStyle(item, option) {
    const {
        start,
        // end,
        interval
    } = {
        ...option
    }
    let startTime, duringTime, missionStartTime, color='#4bd6e9';
    if (item.start) {
        missionStartTime = getDate(item.start).getTime()
        startTime = (missionStartTime - (getDate(start).getTime())) / (ONE_DAY);
        duringTime = ((getDate(item.end).getTime()) - missionStartTime) / (ONE_DAY) + 1;
    }

    let percent = 0;

    switch (item.status) {
        case 'done':
            percent = 100;
            color = '#32ce03'
            break;
        case 'doing':
        case 'create':
        default:
            const today = Date.parse(new Date().toLocaleDateString())
            percent = +(((today - missionStartTime) / (ONE_DAY)) / duringTime * 100).toFixed(0);
            if (percent > 90) percent = 90;
            const delta = (today - getDate(item.end).getTime()) / ONE_DAY;
            if (delta > 0) {
                // const gbValue = (15 - delta) / 15 * 255;
                // color = 'rgb(255,' + gbValue + ',' + gbValue + ')'
                color='#ff3e3e'
            }
            break;
    }
    if (percent < 0) percent = 0;
    let left = startTime * interval;
    let width = (duringTime) * interval;
    let right = left + width;
    return {
        left,
        width,
        right,
        percent,
        color
    }
}

function mixGantt(ganttList) {

    // return;
    j: for (let j = 1; j < ganttList.length; j++) {
        //遍历下层元素列表
        const ganttItemDown = ganttList[j];
        if (ganttItemDown.length) {
            n: for (let n = 0; n < ganttItemDown.length; n++) {
                const itemJ = ganttItemDown[n];
                const itemJStart = getDate(itemJ.start);
                const itemJEnd = getDate(itemJ.end);
                i:
                for (let i = 0; i < j; i++) {
                    //遍历上层元素列表
                    const gantItemUp = ganttList[i];
                    if (gantItemUp.length) {
                        m: for (let m = 0; m < gantItemUp.length; m++) {
                            const itemI = gantItemUp[m];
                            //如果下层起始时间小于上层开始时间
                            if (itemJStart > getDate(itemI.end)) {
                                if (m < gantItemUp.length - 1) {
                                    //但上层元素后方还有其他元素
                                    if (itemJEnd < getDate(gantItemUp[m + 1].start)) {
                                        //偏偏下层元素终止时间小于上层元素后方元素的开始时间
                                        //向上合并之
                                        ganttList[i] = insetIntoArray(gantItemUp, itemJ, m);
                                        ganttItemDown.splice(n, 1);
                                        n--;
                                        break i;
                                    }
                                } else {
                                    //并且上层元素后方不再有元素
                                    gantItemUp.push(itemJ);
                                    ganttItemDown.splice(n, 1);
                                    n--;
                                    break i;
                                }
                            } else if (itemJEnd < getDate(itemI.start)) {
                                //或者下层终止时间小于上层起始时间
                                if (m > 0) {       //但前面还有任务
                                    if (itemJStart > getDate(gantItemUp[m - 1].end)) {
                                        //但是任务的终止时间小于下层任务的起始时间
                                        ganttList[i] = insetIntoArray(gantItemUp, itemJ, m);
                                        ganttItemDown.splice(n, 1);
                                        n--;
                                        break i;
                                    }
                                } else {
                                    gantItemUp.push(itemJ);
                                    ganttItemDown.splice(n, 1);
                                    n--;
                                    break i;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}